package org.ryaness.demo.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import org.ryaness.demo.DemoApplication;
import org.ryaness.demo.util.Md5Utils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

@Service
public class DemoService {

    private static final String OPT_RAW_DIR = "D:/test_dir/opt/raw";

    private static final String DEST_DIR = "D:/test_dir/dest";

    private static int counter = 0;

    public void upload(MultipartFile zipFile) {

        // 根目录&解压缩
        File rootFolder;
        try {
            rootFolder = ZipUtil.unzip(zipFile.getInputStream(), new File(OPT_RAW_DIR), Charset.forName("GBK"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 学季目录
        File[] yearQuarterFolder = FileUtil.ls(rootFolder.getAbsolutePath());

        Arrays.stream(yearQuarterFolder).flatMap(yqFolder -> {
                    // 代码目录
                    File[] subscripCodeFolders = FileUtil.ls(yqFolder.getAbsolutePath());

                    if(StrUtil.length(yqFolder.getName())!=6){
                        throw new RuntimeException("学季目录错误");
                    }

                    String year = yqFolder.getName().substring(0, 4);
                    String quarterName = yqFolder.getName().substring(4);

                    return Arrays.stream(subscripCodeFolders).map(subscripCodeFolder -> {

                        String subscripCode = subscripCodeFolder.getName();

                        File[] files = FileUtil.ls(subscripCodeFolder.getAbsolutePath());

                        return new DemoApplication.FolderInfo().setYear(year).setQuarterName(quarterName).setSubscripCode(subscripCode).setFiles(files);
                    });
                })
                .forEach(folderInfo->{

                    Arrays.stream(folderInfo.getFiles()).forEach(file->{

                        if("01".equals(FileUtil.mainName(file.getName())) || "02".equals(FileUtil.mainName(file.getName())) ){ // 封面
                            try {
                                coverPicture(file, new File(DEST_DIR));
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }else{ // 详情
                            try {
                                detailPicture(file, new File(DEST_DIR));
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }

                    });
                });

        cleanRawFolder();
    }

    /**
     * 封面文件处理
     */
    private void coverPicture(File file, File destFolder) throws Exception {
        // 拓展名
        String extName = FileUtil.extName(file);

        String fileMainName = FileUtil.mainName(file.getName());

        BufferedImage image = ImageIO.read(file);

        int height = image.getHeight();
        int width = image.getWidth();

        int min = Math.min(height, width);

        // 1080*1080新画布
        BufferedImage newImage = new BufferedImage(1080, 1080, BufferedImage.TYPE_INT_RGB);

        int scaledWidth = min==width? 1080*width/height : 1080;
        int scaledHeight = min==width? 1080 : 1080*height/width;

        newImage.getGraphics().setColor(new Color(255,255,255));
        newImage.getGraphics().fillRect(0, 0, newImage.getWidth(), newImage.getHeight());
        newImage.getGraphics().drawImage(image.getScaledInstance(scaledWidth,scaledHeight, Image.SCALE_SMOOTH), (1080-scaledWidth)/2, (1080-scaledHeight)/2, null);

        // 输出文件
        File dealedFile = FileUtil.touch(destFolder + "/" + encodingFilename(fileMainName) + "." + extName);
        ImageIO.write(newImage,extName, dealedFile);
    }

    /**
     * 详情图处理
     */
    private void detailPicture(File file, File destFolder) throws Exception {

        // 拓展名
        String extName = FileUtil.extName(file);

        // 文件名
        String fileMainName = FileUtil.mainName(file);

        BufferedImage image = ImageIO.read(file);

        // 按最大2000的高度进行裁剪
        int height = image.getHeight();
        int offset = 2000;
        int index = 0;
        int i=0;
        do {
            int subHeight = index + offset < height ? offset : height - index;
            BufferedImage subImage = image.getSubimage(0, index, image.getWidth(), subHeight);
            File dealedFile = FileUtil.touch(destFolder + "/" + encodingFilename(fileMainName + "-" + (i++)) + "." + extName);
            ImageIO.write(subImage,extName, dealedFile);
            index += subHeight;
        }while(index < height);
    }

    public void cleanRawFolder(){
        FileUtil.del(OPT_RAW_DIR);
    }

    public static String encodingFilename(String fileName) {
//        fileName = fileName.replace("_", " ");
//        fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++);
        return fileName;
    }

}
